package service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import common.ServerResponse;
import domain.address;
import domain.orders;
import domain.product;
import domain.order_detail;
import domain.shoppingcart;
import service.IOrderService;
import util.bigDecimalUtil;
import util.jdbcUtil;
import vo.AddressVO;
import vo.OrderDetailVO;
import vo.OrderVO;

public class OrderServiceImpl implements IOrderService {
	
	/***创建订单*************************************************/
	public ServerResponse create(Object obj_session_user_id,String address_id) {
		//获取创建订单时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String create_time=sdf.format(date);
		String update_time=sdf.format(date);		
		//sql语句
		String sql1="select * from shoppingcart where user_id=? and checked=1";
		String sql2="insert into order_detail(order_no,user_id,product_id,product_name,product_image,current_unit_price,quantity,total_price,create_time,update_time) values (?,?,?,?,?,?,?,?,?,?)";
		
		//登录判断
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("user_id为空，未登录");
		}
		System.out.println("user_id不为空，已登录");
		Long user_id=(Long)obj_session_user_id;
		
		//1.非空校验
		if(address_id==null) {
			return ServerResponse.serverResponseByError("address_id不能为空");
		}
		//2.根据user_id查询购物车中已选择商品->List<cart>
		List<shoppingcart> cartList= new ArrayList<shoppingcart>();
		cartList = jdbcUtil.select(shoppingcart.class, sql1, user_id);
		//3.List<cart>->List<order_detail>
		ServerResponse serverResponse = getCartOrderDetail(user_id, cartList);
		if(!serverResponse.isSuccess()) {//如果getCartOrderDetail()结果是错误
			return serverResponse;//将错误信息返回
		}
			//不是错误，继续
		//4.创建订单order并将其保存到数据库
			//计算订单总价
		BigDecimal orderTotalPrice=new BigDecimal("0");
		List<order_detail> orderDetailList=(List<order_detail>) serverResponse.getData();
		if(orderDetailList==null||orderDetailList.size()==0) {
			return ServerResponse.serverResponseByError("购物车为空");
		}
		orderTotalPrice=getOrderTotalPrice(orderDetailList);
		orders order=createOrder(user_id, address_id, orderTotalPrice);
		if(order==null) {
			return ServerResponse.serverResponseByError("订单创建失败");
		}
		//5.将List<order_detail>保存到数据库
		for(order_detail orderDetail:orderDetailList) {
			orderDetail.setOrder_no(order.getOrder_no());
			//批量插入
			int i =jdbcUtil.update(sql2, orderDetail.getOrder_no(),
										 orderDetail.getUser_id(),
										 orderDetail.getProduct_id(),
										 orderDetail.getProduct_name(),
										 orderDetail.getProduct_image(),
										 orderDetail.getCurrent_unit_price(),
										 orderDetail.getQuantity(),
										 orderDetail.getTotal_price(),
										 create_time,
										 update_time);
			if(i==0) {
				return ServerResponse.serverResponseByError("保存数据失败");
			}
		}
		//6.减少商品库存
		reduceProductStock(orderDetailList);
		//7.清空购物车中已下单商品
		cleanCart(cartList);
		//8.返回OrderVO
		OrderVO orderVO = assembleOrderVO(order, orderDetailList, Long.valueOf(address_id));
		
		return ServerResponse.serverResponseBySuccess(orderVO);
	}
	
	private ServerResponse getCartOrderDetail(Long user_id,List<shoppingcart> cartList) {
		//sql语句
		String sql1="select * from product where id=?";
		if(cartList==null||cartList.size()==0) {
			return ServerResponse.serverResponseByError("购物车是空的");
		}
		List<order_detail> orderDetailList = new ArrayList<order_detail>();
		for(shoppingcart cart:cartList) {
			order_detail orderDetail = new order_detail();
			orderDetail.setUser_id(user_id);
			List<product> product = jdbcUtil.select(product.class, sql1, cart.getProduct_id());
			System.out.println("product数组"+product);
			if(product.get(0)==null) {
				return ServerResponse.serverResponseByError("product_id为"+cart.getProduct_id()+"的商品不存在");
			}
			if(product.get(0).getStatus()!=1) {//商品已下架
				return ServerResponse.serverResponseByError("product_id为"+cart.getProduct_id()+"的商品已下架");
			}
			if(product.get(0).getStock() < cart.getQuantity()) {//库存不足
				return ServerResponse.serverResponseByError("product_id为"+cart.getProduct_id()+"的商品库存不足");
			}
			orderDetail.setQuantity(cart.getQuantity());
			orderDetail.setCurrent_unit_price(product.get(0).getPrice());
			orderDetail.setProduct_id(product.get(0).getId());
			orderDetail.setProduct_image(product.get(0).getMain_image());
			orderDetail.setProduct_name(product.get(0).getName());
			orderDetail.setTotal_price(bigDecimalUtil.mul(product.get(0).getPrice().doubleValue(), cart.getQuantity().doubleValue()));
			
			orderDetailList.add(orderDetail);
			
		}
		return ServerResponse.serverResponseBySuccess(orderDetailList);
	}
	/***创建订单***/
	private orders createOrder(Long user_id,String address_id,BigDecimal orderTotalPrice) {
		//获取创建订单时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String create_time=sdf.format(date);
		String update_time=sdf.format(date);
		//sql语句
		String sql1="insert into orders(order_no,user_id,address_id,payment,payment_type,postage,status,create_time,update_time) values (?,?,?,?,?,?,?,?,?) ";
		
		orders order=new orders();
		order.setOrder_no(generateOrderNo().toString());
		order.setUser_id(user_id);
		order.setAddress_id(Long.valueOf(address_id));
		order.setStatus((long) 1);//未付款
		//订单金额
		order.setPayment(orderTotalPrice);
		order.setPostage(BigDecimal.valueOf(0));
		order.setPayment_type((long) 1);//本项目只有线上支付
		
		//保存订单
		int i = jdbcUtil.update(sql1, order.getOrder_no(),
									  order.getUser_id(),
									  order.getAddress_id(),
									  order.getPayment(),
									  order.getPayment_type(),
									  order.getPostage(),
									  order.getStatus(),
									  create_time,
									  update_time);
		if(i>0) {
			return order;
		}
		return null;
	}
	/***生成订单编号的规则(唯一)***/
	private Long generateOrderNo() {
		return System.currentTimeMillis()+new Random().nextInt(100);//13位精确到毫秒的时间戳+100以内随机数
	}
	/***计算订单总价***/
	private BigDecimal getOrderTotalPrice(List<order_detail> orderDetailList) {
		BigDecimal bigDecimal=new BigDecimal("0");
		for(order_detail orderDetail:orderDetailList) {
			bigDecimal=bigDecimalUtil.add(bigDecimal.doubleValue(), orderDetail.getTotal_price().doubleValue());
		}
		
		return bigDecimal;
	}
	/***扣库存方法***/
	private void reduceProductStock(List<order_detail> orderDetailList) {
		//获取更新时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String update_time=sdf.format(date);
		//sql语句
		String sql1="select * from product where id=?";
		String sql2="update product set stock=?,update_time=? where id=?";
		if(orderDetailList!=null&&orderDetailList.size()>0) {
			for(order_detail orderDetail:orderDetailList) {
				Long product_id=orderDetail.getProduct_id();
				Long quantity=orderDetail.getQuantity();
				List<product> product = jdbcUtil.select(product.class, sql1, product_id);
				product.get(0).setStock(product.get(0).getStock()-quantity);
				int i = jdbcUtil.update(sql2, product.get(0).getStock(),update_time,product_id);
			}
		}
	}
	/***清空购物车中已选择的商品***/
	private void cleanCart(List<shoppingcart> cartList) {
		//sql语句
		String sql1="delete from shoppingcart where id=?";
		if(cartList!=null&&cartList.size()!=0) {
			for(shoppingcart cart:cartList) {
				Long id=cart.getId();
				int i =jdbcUtil.update(sql1, id);
			}
		}
	}
	/***获取OrderVO***/
	private OrderVO assembleOrderVO(orders order,List<order_detail> orderDetailList,Long address_id) {
		//sql语句
		String sql1="select * from address where id=?";
		OrderVO orderVO = new OrderVO();
		
		List<OrderDetailVO> orderDetailVOList = new ArrayList<OrderDetailVO>();
		for(order_detail orderDetail:orderDetailList) {
			OrderDetailVO orderDetailVO=assembleOrderDetailVO(orderDetail);
			orderDetailVOList.add(orderDetailVO);
		}
		orderVO.setOrderDetailVOList(orderDetailVOList);
		orderVO.setImageHost("图片域名");
		List<address> address = jdbcUtil.select(address.class, sql1, address_id);
		if(address.get(0)!=null) {
			orderVO.setAddress_id(address_id);
			AddressVO addressVO = assembleAddressVO(address.get(0));
			orderVO.setAddressVO(addressVO);
			orderVO.setReceiver_name(address.get(0).getReceiver_name());
		}
		
		orderVO.setStatus(order.getStatus());
		String statusDesc="";
		switch (order.getStatus().intValue()) {
		case 0:
			statusDesc="已取消";
			break;
		case 1:
			statusDesc="未付款";
			break;
		case 2:
			statusDesc="已付款";
			break;
		case 3:
			statusDesc="已发货";
			break;
		case 4:
			statusDesc="交易成功";
			break;
		case 5:
			statusDesc="交易关闭";
			break;
		default:
			statusDesc="错误的状态";
			break;
		}
		orderVO.setStatusDesc(statusDesc);
		orderVO.setPostage(BigDecimal.valueOf(0));
		orderVO.setPayment(order.getPayment());
		orderVO.setPayment_type(order.getPayment_type());
		orderVO.setPaymentTypeDesc("在线支付");//本项目只有在线支付
		orderVO.setOrder_no(order.getOrder_no());
		
		return orderVO;
	}
	
	/***转换list***/
	private OrderDetailVO assembleOrderDetailVO(order_detail orderDetail) {
		OrderDetailVO orderDetailVO = new OrderDetailVO();
		if(orderDetail!=null) {
			orderDetailVO.setQuantity(orderDetail.getQuantity());
			orderDetailVO.setCreate_time(orderDetail.getCreate_time());
			orderDetailVO.setCurrent_unit_price(orderDetail.getCurrent_unit_price());
			orderDetailVO.setOrder_no(orderDetail.getOrder_no());
			orderDetailVO.setProduct_id(orderDetail.getProduct_id());
			orderDetailVO.setProduct_image(orderDetail.getProduct_image());
			orderDetailVO.setProduct_name(orderDetail.getProduct_name());
			orderDetailVO.setTotal_price(orderDetail.getTotal_price());
		}
		return orderDetailVO;
	}
	/***获取AddressVO***/
	private AddressVO assembleAddressVO(address address) {
		AddressVO addressVO=new AddressVO();
		if(address!=null) {
			addressVO.setReceiver_city(address.getReceiver_city());
			addressVO.setReceiver_district(address.getReceiver_district());
			addressVO.setReceiver_mobile(address.getReceiver_mobile());
			addressVO.setReceiver_name(address.getReceiver_name());
			addressVO.setReceiver_phone(address.getReceiver_phone());
			addressVO.setReceiver_province(address.getReceiver_province());
			addressVO.setReceiverZip(address.getReceiver_zip());
		}
		
		
		
		return addressVO;
	}
	
	/*****************************************************/
	/*************************************************************/
	/********************************************************/
	//获取订单的商品信息
	public ServerResponse get_order_cart_product(Object obj_session_user_id, String order_no) {
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("用户未登录");
		}
		if(order_no==null||order_no=="") {
			return ServerResponse.serverResponseByError("参数不能为空");
		}
		String sql="select * from orders where order_no=?";
		List<orders> li=jdbcUtil.select(orders.class, sql, order_no);
		if(li.size()<=0) {
			return ServerResponse.serverResponseByError("error:该订单不存在");
		}
		return BackOrdervo(li, 0);
	}

	//订单List
	public ServerResponse list(String pageSize, String pageNum, Object obj_session_user_id) {
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("用户未登录");
		}
		Long user_id=(Long)obj_session_user_id;
//		Long user_id=(long) 1;
		List<orders>ll =jdbcUtil.select(orders.class, "select * from orders where user_id=?", user_id);
	    int count=ll.size();
	    if(count<=0) {
	    	return ServerResponse.serverResponseByError("error:该用户无数据");
	    }
		String sql0="select * from orders where user_id = ? limit ?,?";
		long pagenum=Long.parseLong(pageNum);
		if(pagenum<=0) {
			return ServerResponse.serverResponseByError("页码不合法");
		}
		long pagesize=Long.parseLong(pageSize);
		List<orders> order=jdbcUtil.select(orders.class, sql0, user_id,(pagenum-1)*pagesize,pagesize);
		if(order.size()>0) {
			return BackOrdervo(order, count);
		}
		else {
			return ServerResponse.serverResponseByError("error:无数据");
		}


	}
	
	//订单详情detail
	public ServerResponse detail(Object obj_session_user_id, String order_no) {
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("用户未登录");
		}
		if(order_no==null) {
			return ServerResponse.serverResponseByError("参数不能为空");
		}
		String sql="select * from orders where order_no=?";
		List<orders> li=jdbcUtil.select(orders.class, sql, order_no);
		if(li.size()<=0) {
			return ServerResponse.serverResponseByError("error:该订单不存在");
		}
		return BackOrdervo(li, 0);
		
	}
	
	//取消订单
	public ServerResponse cancel(String order_no,Object obj_session_user_id) {
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("用户未登录");
		}
		
		if(order_no==null||order_no=="") {
			return ServerResponse.serverResponseByError("参数不能为空");
		}
		String sql="select * from orders where order_no = ?";
		List<orders> odlist=jdbcUtil.select(orders.class, sql, order_no);
		if(odlist.size()<=0) {
			return ServerResponse.serverResponseByError("error:订单已不存在");
		}
		orders od=odlist.get(0);
		long st=od.getStatus();
		if(st>1) {
			return ServerResponse.serverResponseByError("error:此订单已支付，无法取消");
		}
		String sql1="delete from orders where order_no = ?";
		String sql2="delete from order_detail where order_no = ?";
		int i =jdbcUtil.update(sql1, order_no);
		int j =jdbcUtil.update(sql2, order_no);
		if(i>0||j>0) {
			return ServerResponse.serverResponseBySuccess();
		}
		else {
			return ServerResponse.serverResponseByError("error:删除失败，可能不存在");
		}
	}
	
	//获取ordervo并返回,其中count>0时候肯定为list操作，=0为其他操作
		private ServerResponse BackOrdervo(List<orders> orderslist,int count){
			  //遍历
		    List<OrderVO> biglist=new ArrayList<OrderVO>();
		    for(orders o:orderslist) {
		    	OrderVO ordervo=new OrderVO();
		    	ordervo.setOrder_no(o.getOrder_no());
		    	ordervo.setPayment(o.getPayment());
		    	ordervo.setPayment_type(o.getPayment_type());
		    	ordervo.setPaymentTypeDesc(ToTypeDesc(o.getPayment_type()));
		    	ordervo.setPostage(o.getPostage());
		    	ordervo.setStatus(o.getStatus());
		    	ordervo.setStatusDesc(ToStatusDesc(o.getStatus()));
		    	ordervo.setPayment_time(o.getPayment_time());
		    	ordervo.setSend_time(o.getSend_time());
		    	ordervo.setEnd_time(o.getEnd_time());
		    	ordervo.setClose_time(o.getClose_time());
		    	ordervo.setCreate_time(o.getCreate_time());
		    	
		    	/////////
		    	//接下来添加detailList//////
		    	///////////
		    	//遍历当前order_no订单对应所有detail
		    	String detailsql="select * from order_detail where order_no=?";
		    	List<order_detail> dlist=jdbcUtil.select(order_detail.class, detailsql, o.getOrder_no());
		    	if(dlist.size()<=0) {
		    		return ServerResponse.serverResponseByError("error:该订单的详细情况不在数据库中");
		    	}
		    	List<OrderDetailVO> DVlist=new ArrayList<OrderDetailVO>();//存每个OrderDetailVO
		    	for(order_detail od:dlist) {
		    		OrderDetailVO odvo=new OrderDetailVO();
		    		odvo.setOrder_no(od.getOrder_no());
		    		odvo.setProduct_id(od.getProduct_id());
		    		odvo.setProduct_name(od.getProduct_name());
		    		odvo.setProduct_image(od.getProduct_image());
		    		odvo.setCurrent_unit_price(od.getCurrent_unit_price());
		    		odvo.setQuantity(od.getQuantity());
		    		odvo.setTotal_price(od.getTotal_price());
		    		odvo.setCreate_time(od.getCreate_time());
		    		DVlist.add(odvo);
		    	}
		    	//将orderItemVoList数组加入进去
		    	ordervo.setOrderDetailVOList(DVlist);
		    	ordervo.setImageHost("???");
		    	ordervo.setAddress_id(o.getAddress_id());
		    	
		    	////////////
		    	//addressvo操作区
		    	//////////
		    	String asql="select * from address where id=?";
		    	List<address> al=jdbcUtil.select(address.class,asql, o.getAddress_id());
		    	if(al.size()<=0) {
		    		return ServerResponse.serverResponseByError("error:此订单的详细地址不在数据库中");
		    	}
		    	address a=al.get(0);
		    	//装addressVO的箱
		    	AddressVO avo=new AddressVO();
		    	avo.setReceiver_name(a.getReceiver_name());
		    	avo.setReceiver_phone(a.getReceiver_phone());
		    	avo.setReceiver_mobile(a.getReceiver_mobile());
		    	avo.setReceiver_province(a.getReceiver_province());
		    	avo.setReceiver_city(a.getReceiver_city());
		    	avo.setReceiver_district(a.getReceiver_district());
		    	avo.setReceiverZip(a.getReceiver_zip());
		    	ordervo.setAddressVO(avo);
		    	
		    	//最后添加到最大数组中///
		    	biglist.add(ordervo);
		    }
		    	return ServerResponse.serverResponseBySuccess(count, biglist, "ok");
		}

	private String ToTypeDesc(long p) {
		if(p==1) {
			return "在线支付";
		}else {
			return "货到付款";
		}
	}
	private String ToStatusDesc(long s) {
		if(s==0) {
			return "已取消";
		}
		else if(s==1) {
			return "未付款";
		}
		else if(s==2) {
			return "已付款";
		}
		else if(s==3) {
			return "已发货";
		}
		else if(s==4) {
			return "交易成功";
		}
		else {
			return "交易关闭";
		}
	}
	
	

}
